package com.example.studentknowledge.controller;

import com.example.studentknowledge.entity.Article;
import com.example.studentknowledge.entity.Comment;
import com.example.studentknowledge.entity.User;
import com.example.studentknowledge.service.ArticleService;
import com.example.studentknowledge.service.CommentService;
import com.example.studentknowledge.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * 评论控制器
 */
@RestController
@RequestMapping("/api/comments")
@CrossOrigin(origins = "*")
public class CommentController {
    
    @Autowired
    private CommentService commentService;
    
    @Autowired
    private ArticleService articleService;
    
    @Autowired
    private UserService userService;
    
    /**
     * 创建评论
     */
    @PostMapping
    @PreAuthorize("isAuthenticated()")
    public ResponseEntity<?> createComment(@Valid @RequestBody Comment comment, Authentication authentication) {
        try {
            String username = authentication.getName();
            Optional<User> user = userService.findByUsername(username);
            
            if (user.isPresent()) {
                comment.setUser(user.get());
                
                // 检查文章是否存在
                Optional<Article> article = articleService.findById(comment.getArticle().getId());
                if (!article.isPresent()) {
                    Map<String, Object> response = new HashMap<>();
                    response.put("success", false);
                    response.put("message", "文章不存在");
                    return ResponseEntity.badRequest().body(response);
                }
                
                comment.setArticle(article.get());
                
                // 如果是回复评论，检查父评论是否存在
                if (comment.getParent() != null && comment.getParent().getId() != null) {
                    Optional<Comment> parent = commentService.findById(comment.getParent().getId());
                    if (!parent.isPresent()) {
                        Map<String, Object> response = new HashMap<>();
                        response.put("success", false);
                        response.put("message", "父评论不存在");
                        return ResponseEntity.badRequest().body(response);
                    }
                    comment.setParent(parent.get());
                } else {
                    comment.setParent(null);
                }
                
                Comment savedComment = commentService.createComment(comment);
                
                Map<String, Object> response = new HashMap<>();
                response.put("success", true);
                response.put("message", "评论创建成功");
                response.put("comment", savedComment);
                return ResponseEntity.ok(response);
            } else {
                Map<String, Object> response = new HashMap<>();
                response.put("success", false);
                response.put("message", "用户不存在");
                return ResponseEntity.badRequest().body(response);
            }
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    /**
     * 更新评论
     */
    @PutMapping("/{id}")
    @PreAuthorize("isAuthenticated()")
    public ResponseEntity<?> updateComment(@PathVariable Long id, @Valid @RequestBody Comment comment, Authentication authentication) {
        try {
            String username = authentication.getName();
            Optional<User> user = userService.findByUsername(username);
            
            if (user.isPresent()) {
                Optional<Comment> existingComment = commentService.findById(id);
                if (!existingComment.isPresent()) {
                    Map<String, Object> response = new HashMap<>();
                    response.put("success", false);
                    response.put("message", "评论不存在");
                    return ResponseEntity.badRequest().body(response);
                }
                
                // 检查是否有权限编辑评论
                if (!commentService.canEditComment(existingComment.get(), user.get())) {
                    Map<String, Object> response = new HashMap<>();
                    response.put("success", false);
                    response.put("message", "没有权限编辑该评论");
                    return ResponseEntity.badRequest().body(response);
                }
                
                // 只更新内容
                Comment commentToUpdate = existingComment.get();
                commentToUpdate.setContent(comment.getContent());
                
                Comment updatedComment = commentService.updateComment(commentToUpdate);
                
                Map<String, Object> response = new HashMap<>();
                response.put("success", true);
                response.put("message", "评论更新成功");
                response.put("comment", updatedComment);
                return ResponseEntity.ok(response);
            } else {
                Map<String, Object> response = new HashMap<>();
                response.put("success", false);
                response.put("message", "用户不存在");
                return ResponseEntity.badRequest().body(response);
            }
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    /**
     * 根据ID获取评论
     */
    @GetMapping("/{id}")
    public ResponseEntity<?> getCommentById(@PathVariable Long id) {
        try {
            Optional<Comment> comment = commentService.findById(id);
            if (comment.isPresent()) {
                return ResponseEntity.ok(comment.get());
            } else {
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    /**
     * 根据文章获取评论
     */
    @GetMapping("/article/{articleId}")
    public ResponseEntity<?> getCommentsByArticle(
            @PathVariable Long articleId,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        try {
            Optional<Article> article = articleService.findById(articleId);
            if (article.isPresent()) {
                Pageable pageable = PageRequest.of(page, size);
                Page<Comment> comments = commentService.getCommentsByArticle(article.get(), pageable);
                return ResponseEntity.ok(comments);
            } else {
                Map<String, Object> response = new HashMap<>();
                response.put("success", false);
                response.put("message", "文章不存在");
                return ResponseEntity.badRequest().body(response);
            }
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    /**
     * 获取文章的顶级评论（非回复）
     */
    @GetMapping("/article/{articleId}/top-level")
    public ResponseEntity<?> getTopLevelCommentsByArticle(@PathVariable Long articleId) {
        try {
            Optional<Article> article = articleService.findById(articleId);
            if (article.isPresent()) {
                List<Comment> comments = commentService.getTopLevelComments(article.get());
                return ResponseEntity.ok(comments);
            } else {
                Map<String, Object> response = new HashMap<>();
                response.put("success", false);
                response.put("message", "文章不存在");
                return ResponseEntity.badRequest().body(response);
            }
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    /**
     * 获取评论的回复
     */
    @GetMapping("/{commentId}/replies")
    public ResponseEntity<?> getRepliesByComment(@PathVariable Long commentId) {
        try {
            Optional<Comment> comment = commentService.findById(commentId);
            if (comment.isPresent()) {
                List<Comment> replies = commentService.getReplies(comment.get());
                return ResponseEntity.ok(replies);
            } else {
                Map<String, Object> response = new HashMap<>();
                response.put("success", false);
                response.put("message", "评论不存在");
                return ResponseEntity.badRequest().body(response);
            }
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    /**
     * 根据用户获取评论
     */
    @GetMapping("/user/{userId}")
    public ResponseEntity<?> getCommentsByUser(
            @PathVariable Long userId,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        try {
            Optional<User> user = userService.findById(userId);
            if (user.isPresent()) {
                Pageable pageable = PageRequest.of(page, size);
                Page<Comment> comments = commentService.getCommentsByUser(user.get(), pageable);
                return ResponseEntity.ok(comments);
            } else {
                Map<String, Object> response = new HashMap<>();
                response.put("success", false);
                response.put("message", "用户不存在");
                return ResponseEntity.badRequest().body(response);
            }
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    /**
     * 获取我的评论
     */
    @GetMapping("/my")
    @PreAuthorize("isAuthenticated()")
    public ResponseEntity<?> getMyComments(
            Authentication authentication,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        try {
            String username = authentication.getName();
            Optional<User> user = userService.findByUsername(username);
            
            if (user.isPresent()) {
                Pageable pageable = PageRequest.of(page, size);
                Page<Comment> comments = commentService.getCommentsByUser(user.get(), pageable);
                return ResponseEntity.ok(comments);
            } else {
                Map<String, Object> response = new HashMap<>();
                response.put("success", false);
                response.put("message", "用户不存在");
                return ResponseEntity.badRequest().body(response);
            }
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    /**
     * 搜索评论
     */
    @GetMapping("/search")
    public ResponseEntity<?> searchComments(
            @RequestParam String keyword,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        try {
            Pageable pageable = PageRequest.of(page, size);
            Page<Comment> comments = commentService.searchComments(keyword, pageable);
            return ResponseEntity.ok(comments);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    /**
     * 获取最新评论
     */
    @GetMapping("/latest")
    public ResponseEntity<?> getLatestComments(@RequestParam(defaultValue = "10") int limit) {
        try {
            List<Comment> comments = commentService.getLatestComments(limit);
            return ResponseEntity.ok(comments);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    /**
     * 删除评论
     */
    @DeleteMapping("/{id}")
    @PreAuthorize("isAuthenticated()")
    public ResponseEntity<?> deleteComment(@PathVariable Long id, Authentication authentication) {
        try {
            String username = authentication.getName();
            Optional<User> user = userService.findByUsername(username);
            
            if (user.isPresent()) {
                Optional<Comment> comment = commentService.findById(id);
                if (!comment.isPresent()) {
                    Map<String, Object> response = new HashMap<>();
                    response.put("success", false);
                    response.put("message", "评论不存在");
                    return ResponseEntity.badRequest().body(response);
                }
                
                // 检查是否有权限删除评论
                if (!commentService.canDeleteComment(comment.get(), user.get())) {
                    Map<String, Object> response = new HashMap<>();
                    response.put("success", false);
                    response.put("message", "没有权限删除该评论");
                    return ResponseEntity.badRequest().body(response);
                }
                
                commentService.deleteComment(id);
                
                Map<String, Object> response = new HashMap<>();
                response.put("success", true);
                response.put("message", "评论删除成功");
                return ResponseEntity.ok(response);
            } else {
                Map<String, Object> response = new HashMap<>();
                response.put("success", false);
                response.put("message", "用户不存在");
                return ResponseEntity.badRequest().body(response);
            }
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
}